package util

import (
	"bytes"
	"crypto/md5"
	"crypto/sha256"
	"encoding/hex"
	"fmt"
	"io/ioutil"
	"k8s.io/apimachinery/pkg/util/yaml"
	"log"
	"path/filepath"
	"sort"
	"strings"
	"time"
)

//首字母大写
func FirstUpper(org string) string {
	return strings.ToUpper(org[:1]) + org[1:]
}

//yaml to 字节数组
func Yamls2Bytes(rootPath string, files []string) [][]byte {
	yamls := make([][]byte, len(files))
	for i, name := range files {
		yamlBytes, err := ioutil.ReadFile(filepath.Join(rootPath, name))
		if err != nil {
			log.Println(err.Error())
		}
		yamls[i] = yamlBytes

	}
	return yamls
}

//yaml to json
func Yamls2Jsons(data [][]byte) [][]byte {
	jsons := make([][]byte, 0)
	for _, yamlBytes := range data {
		yamls := bytes.Split(yamlBytes, []byte("---"))
		for _, v := range yamls {
			if len(v) == 0 {
				continue
			}
			obj, err := yaml.ToJSON(v)
			if err != nil {
				log.Println(err.Error())
			}
			jsons = append(jsons, obj)
		}

	}
	return jsons
}

// Ksort 参数升序排序
func Ksort(paramsMap map[string]string) string {
	var slice []string
	for key, _ := range paramsMap {
		slice = append(slice, key)
	}
	sort.Strings(slice)
	/*	str := url.Values{}
			for num, key := range slice {
				if num == 0 {
					str.Set(key, paramsMap[key])
				} else {
					str.Add(key, paramsMap[key])
				}
			}
			strParams := str.Encode()
		return strParams
	*/
	var str string
	for i := len(slice) - 1; i >= 0; i-- {
		str += fmt.Sprintf("%s=%s", slice[i], paramsMap[slice[i]])
		if i != 0 {
			str += "&"
		}
	}

	return str
}

func GetSha256Hash(content string) (hash string) {
	sha := sha256.New()
	sha.Write([]byte(content))
	hashHex := sha.Sum(nil)
	//由于是十六进制表示，因此需要转换
	hash = hex.EncodeToString(hashHex)
	return
}

func GetAppkey() string {
	timestamp := fmt.Sprint(time.Now().UnixNano() / 1e6)

	m := md5.New()
	m.Write([]byte(timestamp))
	key := hex.EncodeToString(m.Sum(nil))
	return key
}
